#include "recvfileclass.h"

static const QString address="127.0.0.1";
static const quint64 port=8890;

RecvFileClass::RecvFileClass(QObject *parent) : QObject(parent)
{
    recvfile=nullptr;
    recvfilesocket=nullptr;
}

void RecvFileClass::initRecvFileClass(const QString& useroc)
{
    recvfilesocket=new QTcpSocket;
    recvfilesocket->connectToHost(address,port);
    connect(recvfilesocket,&QTcpSocket::readyRead,this,&RecvFileClass::verify);
    connect(JSHandler::getInstance(),&JSHandler::s_recvFileHead,this,&RecvFileClass::dealRecvFileHead);
    connect(CustomHandler::getInstance(),&CustomHandler::s_fileBlock,this,&RecvFileClass::dealFileBlock);
    connect(JSHandler::getInstance(),&JSHandler::s_fileEnd,this,&RecvFileClass::fileEnd);
    recvdonesize=0;
    this->useroc=useroc;
}

void RecvFileClass::verify()
{

    QByteArray res=*Encipher::getInstance()->sha_aesDecrypt(recvfilesocket->readAll());

    MyJson::getInstance()->analysisJson(res);

}


QString RecvFileClass::checkIsExist(QString filepath,QString filename,QString lastpath)
{
    int count=1;
    QString tmp;
    QString newpath=filepath;
    QFile file(filepath);
    while(file.exists()){
        tmp=filename;
        //destinationFilePath=QString(dirpath+"["+QString::number(count++)+"]"+filename);
        newpath=QString("%1[%2]%3").arg(lastpath).arg(count++).arg(tmp);
        file.setFileName(newpath);
    }

    return newpath;
}


void RecvFileClass::dealRecvFileHead(const QString &senderoc, const unsigned long filesize, const QString &filesha256, const QString &filename)
{
    QDate date=QDate::currentDate();
    pathdate=QString("/%1-%2/").arg(date.year(), 4, 10, QChar('0')).arg(date.month(), 2, 10, QChar('0'));
    currentfilepath=checkIsExist("./User/"+useroc+"/RecvFile"+pathdate+filename,filename,"./User/"+useroc+"/RecvFile"+pathdate);

    recvfile=new QFile(currentfilepath);
    if(!QDir().exists("./User/"+useroc+"/RecvFile"+pathdate+"/"))
        QDir().mkpath("./User/"+useroc+"/RecvFile"+pathdate+"/");
    if(!recvfile->open(QIODevice::WriteOnly))
        qDebug()<<"new file failed";
    sendFileReady();
    this->senderoc=senderoc;
}

void RecvFileClass::dealFileBlock(const QString &index, const QString &size, const QByteArray &data)
{
    recvfile->write(data);
    sendFileReady();
}

void RecvFileClass::sendFileReady()
{
    QByteArray resmsg=MyJson::getInstance()->fileReady();
    recvfilesocket->write(*Encipher::getInstance()->sha_aesEncrypt(resmsg));
}

void RecvFileClass::fileEnd()
{
    recvfile->close();
    delete  recvfile;
    recvfile=nullptr;
    QFileInfo info(currentfilepath);
    emit s_recvNewFile(senderoc,pathdate+info.fileName());
}
